package com.ff.kvm.service.impl;

import com.aliyuncs.exceptions.ClientException;
import com.ff.kvm.common.eunm.StatusEnum;
import com.ff.kvm.common.third_util.AliyunSmsUtil;
import com.ff.kvm.common.util.Constants;
import com.ff.kvm.common.util.MyUtil;
import com.ff.kvm.common.vo.Response;
import com.ff.kvm.service.RedisService;
import com.ff.kvm.service.SmsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class SmsServiceImpl implements SmsService {


    @Autowired
    private RedisService redisService;

    @Override
    public boolean checkCode(String mobile, String code) {
        if (MyUtil.isBlank(mobile)|| MyUtil.isBlank(code)) {
            return false;
        }
        String value = redisService.getSMSCode(mobile);
        if (value != null && value.equals(code)){
            redisService.delSMSCode(mobile);
            return true;
        }
        return false;
    }

    @Override
    public synchronized boolean sendCode(String mobile, int type, String ip) throws ClientException {
        String[] smsCF = redisService.getCache(Constants.SMS_CF).split("-");
        String code = smsCF[3];
        if (smsCF[0].equals("1")) {
            Response<String> response = AliyunSmsUtil.sendSms(mobile, smsCF[1]);
            if(response.getCode().equals(StatusEnum.SUCCESS.code())){
                code = response.getData();
                redisService.putSMSCode(mobile, code);
                return true;
            }
            return false;
        }
        redisService.putSMSCode(mobile, code);
        return true;
    }

    @Override
    public Response<Boolean> send(String mobile, int type, String ip) {
        Response<Boolean> response = new Response<>();
        boolean rt;
        try {
            rt = sendCode(mobile, type,ip);
        } catch (ClientException e) {
            e.printStackTrace();
            response.setCode(StatusEnum.FAIL.code());
            response.setMsg(StatusEnum.FAIL.description());
            response.setData(false);
            return response;
        }
        if(!rt){
            response.setCode(StatusEnum.FAIL.code());
            response.setMsg(StatusEnum.FAIL.description());
            response.setData(false);
            return response;
        }
        response.setCode(StatusEnum.SUCCESS.code());
        response.setMsg(StatusEnum.SUCCESS.description());
        response.setData(true);
        return response;
    }
}
